package com.example.controller;

import com.example.common.Result;
import com.example.domain.Users;
import com.example.service.UserService;
import com.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*
    登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody Users user){
        Users login_user = userService.login(user);
        if(login_user==null){
            return Result.error();
        }
//        生成token
        String token = TokenUtils.token(user.getUsername(),user.getPassword());

        return Result.success(login_user,token);
    }

    /*
    注册，先添加用户（判断用户名是否已经存在），不存在再添加该用户的个人信息
     */
    @PostMapping("/register")
    public Result register(@RequestBody Users user){
        boolean register = userService.register(user);
        if(!register){
            return Result.error("用户名已存在！");
        }
        return Result.success("注册成功");
    }

}
